import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:exams_app/widget/hexcolor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:convert';

class BulidingMoblePage extends StatefulWidget {

  @override
  _BulidingMoblePageState createState() => _BulidingMoblePageState();

}

class _BulidingMoblePageState extends State<BulidingMoblePage> {


  /// 手机是否已绑定帐号
  ///
  void UpdataDataWithMobile(var mobile,var verifyCode) async {
    String result =
    await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
        .post(
        '/api/v1/exam_verified_mobile/0',
        data: {
          'access_token':await PersistentStorage().getStorage('acctoken'),
          'uid':await PersistentStorage().getStorage('uid'),
          'partner_id':await PersistentStorage().getStorage('partner_id'),
          'mobile': mobile,

          'verifyCode':verifyCode}
          );
    Map json = jsonDecode(result);

    BotToast.showText(text: json['message']);

    Future.delayed(Duration(milliseconds: 500), () {

      Get.back(result: 'refresh');

    });

  }
  /// 发送验证码`
  void sendCodeRequestData(var mobile)async{
    var params = {
      'mobile':mobile,
      'name':'登录确认验证码',
      'n':4,
    };
    String result = await DioUtils(url: await PersistentStorage().getStorage('urlStr')).post('/api/v1/sms/0',data:params);
    Map json = jsonDecode(result);
    BotToast.showText(text: '${json['message']}');

  }

  Timer _timer;

  int _countdownTime = 0;


  void startCountdownTimer(){
    const oneSec = const Duration(seconds: 1);

    var callback = (timer) => {
      setState(() {
        if(_countdownTime<1){
          _timer.cancel();
        }else{
          _countdownTime = _countdownTime -1;
        }
      })
    };

    _timer = Timer.periodic(oneSec,callback);
  }

  @override
  void dispose() {

    super.dispose();

    if(_timer != null){
      _timer.cancel();
    }
  }

  var tf1 = TextEditingController();
  var tf2 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('绑定手机'),
        centerTitle: true,
        actions: [
          TextButton(onPressed: (){

            if(tf1.text.isEmpty){
              BotToast.showText(text: '请输入手机号码');
              return;
            }
            if(tf2.text.isEmpty){
              BotToast.showText(text: '请输入验证码');
              return;
            }
            UpdataDataWithMobile(tf1.text,tf2.text);




          }, child: Text('保存',style: TextStyle(color: Colors.white,fontSize: 16),))
        ],
      ),
      body: ListView(
        children: [
          Container(
            padding: EdgeInsets.only(left: 15),
            color: Colors.white,
            child: TextField(
              controller:tf1 ,
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: '请输入手机号码'
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15,top: 5),
            color: Colors.white,
            child:Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  width: 200,
                  child: TextField(
                    controller:tf2 ,
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '验证码'
                    ),
                  ),
                ),
                TextButton(onPressed: (){

                  if(tf1.text.isEmpty){
                    BotToast.showText(text: '请输入手机号码');
                    return;
                  }
                  startCountdownTimer();
                  if(_countdownTime== 0){

                    setState(() {
                      _countdownTime = 59;
                    });

                    sendCodeRequestData(tf1.text);
                  }


                }, child: Text(
                  _countdownTime > 0?'重新发送(${_countdownTime})':'获取验证码',
                  style: TextStyle(color:_countdownTime > 0
                      ? HexColor('#567BFD')
                      : HexColor(('#567BFD')),fontSize: 14,),
                ),)
              ],
            )
          ),
        ],
      ),
    );
  }
}
